package com.aqie.meet.ui.search;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.aqie.libcommon.adapter.CommonAdapter2;
import com.aqie.libcommon.adapter.CommonViewHolder2;
import com.aqie.libcommon.utils.SimpleJsonTool;
import com.aqie.libfactory.model.api.PageList;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.meet.BusinessBaseFragment2;
import com.aqie.meet.R;
import com.aqie.meet.ui.chat.MessageActivity;
import com.aqie.meet.ui.login.AccountActivity;
import com.aqie.meet.ui.my.FriendHomePageActivity;
import com.aqie.meet.utils.Utils;
import com.aqie.meet.view.AImageView;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import circletextimage.viviant.com.circletextimagelib.view.CircleTextImage;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class SearchTalentFragment extends BusinessBaseFragment2 implements SearchActivity.SearchFragment{

    @BindView(R.id.recycler_view)
    RecyclerView mRecycleView;

    private List<User> mList = new ArrayList<>();
    private CommonAdapter2<User> mAdapter;

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_search_talent;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        initView();
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public void search(String content) {
        getUserList(content);
    }

    private void getUserList(String keyword) {
        RemoteService service = Network.remote();
        Call<RspModel<PageList<User>>> call = service.talents(keyword,1,100);
        call.enqueue(new Callback<RspModel<PageList<User>>>() {
            @Override
            public void onResponse(Call<RspModel<PageList<User>>> call, Response<RspModel<PageList<User>>> response) {
                RspModel<PageList<User>> body = response.body();
                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    PageList<User> talents = body.getData();
                    String rspString = SimpleJsonTool.toJson(talents); Log.e(TAG, rspString);
                    if(talents.getTotal() == 0) {
                        mRecycleView.setVisibility(View.GONE);

                    } else {
                        mRecycleView.setVisibility(View.VISIBLE);
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                        mList.addAll(talents.getRecords());
                        mAdapter.notifyDataSetChanged();
                        Log.e(TAG, "talent list:" + mList.toString());
                    }
                }else {
                    Log.e(TAG, "request fail: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<RspModel<PageList<User>>> call, Throwable t) {
                Log.e(TAG, "request fail: onFailure");
            }
        });
    }

    private void initView() {
        mRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        mAdapter = new CommonAdapter2<>(mList, new CommonAdapter2.OnBindDataListener<User>() {
            @Override
            public void onBindViewHolder(User model, CommonViewHolder2 viewHolder, int type, int position) {
                fillData(model, viewHolder);
                // 切换
                viewHolder.getView(R.id.icon_up).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewHolder.setVisibility(R.id.icon_down, View.VISIBLE);
                        viewHolder.setVisibility(R.id.icon_up, View.GONE);
                        viewHolder.setVisibility(R.id.setting_about_content, View.GONE);
                    }
                });
                viewHolder.getView(R.id.icon_down).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewHolder.setVisibility(R.id.icon_up, View.VISIBLE);
                        viewHolder.setVisibility(R.id.icon_down, View.GONE);
                        viewHolder.setVisibility(R.id.setting_about_content, View.VISIBLE);
                    }
                });
                // 跳转聊天
                viewHolder.getView(R.id.btn_send_message).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(model.getBoolChat() == 2 || model.isBoolFriend()){
                            MessageActivity.show(getActivity(), model.getUserId(),model.getUsername(), true);
                        } else {
                            MessageActivity.show(getActivity(), model.getUserId(),model.getUsername(), false);
                            // BaseApplication.showToast("必须加好友才能聊天");
                        }
                    }
                });


                // 发送添加好友请求
                viewHolder.getView(R.id.btn_add_friend).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // BaseApplication.showToast("添加好友");
                        addFriend(model.getUserId());
                    }
                });

                // 跳转详情
                viewHolder.getView(R.id.tag_avatar_true).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), FriendHomePageActivity.class);
                        intent.putExtra("talentsId", model.getUserId());
                        intent.putExtra("username", model.getUsername());
                        intent.putExtra("isBoolFriend", model.isBoolFriend());
                        startActivity(intent);
                    }
                });

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.talents_item;
            }
        });
        mRecycleView.setAdapter(mAdapter);
        //监听列表滑动
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }

    private void fillData(User model, CommonViewHolder2 viewHolder) {
        CircleTextImage mCircleTextImage = viewHolder.getView(R.id.tag_avatar);
        AImageView mTrueAvatar = viewHolder.getView(R.id.tag_avatar_true);
        if(model != null && model.getAvatar() != null){
            mTrueAvatar.setVisibility(View.VISIBLE);
            mTrueAvatar.setImageUrl(model.getAvatar());
            mCircleTextImage.setVisibility(View.GONE);
        } else {
            // 用户名不为空展示文字头像
            if(model != null && model.getUsername() != null && model.getUsername().length() > 0){
                mCircleTextImage.setText4CircleImage(Utils.getName(model.getUsername()));
            }
        }
        viewHolder.setText(R.id.tag_title, model.getUsername() + " | " + model.getTrade() + " " + model.getPosition());
        viewHolder.setText(R.id.tag_desc, model.getCity() + " " + model.getWorkingYears() + "年工作经验");

        if(TextUtils.isEmpty(model.getCity()) || model.getWorkingYears() == null ){
            viewHolder.goneIfEmpty(R.id.tag_desc);
        }

        // 已经是好友 隐藏添加
        if(model.isBoolFriend()){
            viewHolder.goneIfEmpty(R.id.btn_add_friend);
        }
        viewHolder.setText(R.id.et_resource, model.getAnswerOne());
        viewHolder.setText(R.id.et_need, model.getAnswerTwo());
        viewHolder.setText(R.id.et_know, model.getAnswerThree());
    }
}